package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;


    @Override
    public void clean() {
        //根据用户id进行清空
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(queryWrapper);
    }

    @Override
    public Cart sub(Long dishId, Long setmealId) {
        //根据userid和这俩参数进行查询，如果num>1  就给number-1
        Long user_id =  UserHolder.get().getId();
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId,user_id)
                .eq(dishId != null,Cart::getDishId,dishId)
                .eq(setmealId != null,Cart::getSetmealId,setmealId);
        Cart cart = cartMapper.selectOne(queryWrapper);
        if (cart.getNumber() > 1){
            cart.setNumber(cart.getNumber() -1);
            cartMapper.updateById(cart);
            return cart;
        }else{
            //如果num=1 ,就直接删除这条
            cartMapper.delete(queryWrapper);
            return cart;
        }
    }

    @Override
    public Cart add(Cart cart) {
        //先查询表中有没有，条件就是用户id和dishid或者setmealid
       Long user_id =  UserHolder.get().getId();
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId,user_id)
                    .eq(cart.getDishId() != null,Cart::getDishId,cart.getDishId())
                    .eq(cart.getSetmealId() != null,Cart::getSetmealId,cart.getSetmealId());
        Cart cart1 = cartMapper.selectOne(queryWrapper);
        if (cart1 != null){
            //代表已经有这个商品了 将其number+1即可
            cart1.setNumber(cart1.getNumber() + 1);
            cartMapper.updateById(cart1);
            return cart1;
        }else{
            //代表没有这个商品，新增就好了
            cart.setUserId(user_id);
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            int insert = cartMapper.insert(cart);
            return cart;
        }
    }

    @Override
    public List<Cart> findAll() {
        User user = UserHolder.get();
        //查出购物车
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId,user.getId());
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        return carts;
    }
}
